<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑工商信息</view>
      <view class="nav-right">
        <button class="save-btn" @tap="handleSubmit" :disabled="!canSubmit">
          保存
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 成立时间 -->
      <view class="form-item">
        <view class="form-label">成立时间</view>
        <picker
          mode="date"
          :value="formData.buildDate"
          @change="onBuildDateChange"
        >
          <view class="picker-value">
            <text class="picker-text">{{ formData.buildDate || "请选择成立时间" }}</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>

      <!-- 注册资本 -->
      <view class="form-item">
        <view class="form-label">注册资本</view>
        <input
          class="form-input"
          v-model="formData.registCapital"
          placeholder="请输入注册资本"
          maxlength="50"
        />
      </view>

      <!-- 注册地址 -->
      <view class="form-item">
        <view class="form-label">注册地址</view>
        <view class="address-selector" @tap="openCitySelector">
          <text v-if="formData.registPlace" class="selected-address">{{ formData.registPlace }}</text>
          <text v-else class="address-placeholder">请选择注册地址</text>
          <text class="arrow">></text>
        </view>
      </view>

      <!-- 法人代表 -->
      <view class="form-item">
        <view class="form-label">法人代表</view>
        <input
          class="form-input"
          v-model="formData.legalRepresentative"
          placeholder="请输入法人代表姓名"
          maxlength="20"
        />
      </view>

      <!-- 融资阶段 -->
      <view class="form-item">
        <view class="form-label">融资阶段</view>
        <picker
          mode="selector"
          :range="financingStatusList.map(item => item.value)"
          :value="financingStatusList.findIndex(item => item.value === formData.financStage)"
          @change="onFinancStageChange"
        >
          <view class="picker-value">
            <text class="picker-text">{{ formData.financStage || "请选择融资阶段" }}</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { modifyCompanyInfoApi, getFinancingStatusApi } from "@/api/company.js";

// 获取页面参数
const companyId = ref('');

// 融资状态数据
const financingStatusList = ref([]);

// 表单数据
const formData = ref({
  buildDate: '',
  registCapital: '',
  registPlace: '',
  legalRepresentative: '',
  financStage: ''
});

// 是否可以提交
const canSubmit = computed(() => {
  return true; // 工商信息相关字段都不是必填的
});

// 成立时间选择器变化
const onBuildDateChange = (e) => {
  formData.value.buildDate = e.detail.value;
};

// 打开城市选择器
const openCitySelector = () => {
  console.log('跳转到城市选择页面');
  uni.navigateTo({
    url: '/pages/company/citySelector'
  });
};

// 城市选择回调（供城市选择页面调用）
const onCitySelected = (city) => {
  console.log('收到城市选择结果:', city);
  formData.value.registPlace = city.name;
};

// 融资阶段选择器变化
const onFinancStageChange = (e) => {
  const index = e.detail.value;
  formData.value.financStage = financingStatusList.value[index].value;
};

// 获取融资状态数据
const loadFinancingStatus = async () => {
  try {
    const result = await getFinancingStatusApi();
    if (result && Array.isArray(result)) {
      // 按照 sort 字段排序
      financingStatusList.value = result.sort((a, b) => a.sort - b.sort);
    }
  } catch (error) {
    console.error('获取融资状态数据失败:', error);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (!canSubmit.value) {
      uni.showToast({
        title: '请完善所有必填信息',
        icon: 'none'
      });
      return;
    }

    const updateData = {
      companyId: companyId.value,
      buildDate: formData.value.buildDate,
      registCapital: formData.value.registCapital,
      registPlace: formData.value.registPlace,
      legalRepresentative: formData.value.legalRepresentative,
      financStage: formData.value.financStage
    };

    const result = await modifyCompanyInfoApi(updateData);
    
    // 无论 result 是什么值，只要没有抛出异常就认为保存成功
    console.log('保存结果:', result);
    
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000
    });
    
    // 发送事件通知公司详情页面重新获取数据
    uni.$emit('companyInfoUpdated');
    
    // 跳转回编辑企业页面
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
    
  } catch (error) {
    console.error('保存工商信息失败:', error);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 初始化页面数据
const initPageData = () => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  
  if (options.buildDate) {
    formData.value.buildDate = decodeURIComponent(options.buildDate || '');
  }
  
  if (options.registCapital) {
    formData.value.registCapital = decodeURIComponent(options.registCapital || '');
  }
  
  if (options.registPlace) {
    formData.value.registPlace = decodeURIComponent(options.registPlace || '');
  }
  
  if (options.legalRepresentative) {
    formData.value.legalRepresentative = decodeURIComponent(options.legalRepresentative || '');
  }
  
  if (options.financStage) {
    formData.value.financStage = decodeURIComponent(options.financStage || '');
  }
};

onMounted(async () => {
  try {
    // 初始化页面数据
    initPageData();
    
    // 加载融资状态数据
    await loadFinancingStatus();
    
    // 监听城市选择事件
    uni.$on('citySelected', onCitySelected);
  } catch (error) {
    console.error('页面数据加载失败:', error);
  }
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('citySelected', onCitySelected);
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
}

.save-btn {
  width: 100%;
  height: 60rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 28rpx;
  border: none;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn[disabled] {
  background-color: #c0c0c0;
  color: #fff;
}

.container {
  padding: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.form-input {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
  min-height: 80rpx;
  padding: 12rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  display: block;
  position: relative;
  z-index: 1;
}

.form-input:focus {
  border-color: #007aff;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.picker-value {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 48rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.picker-text {
  flex: 1;
  margin-right: 20rpx;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: calc(100% - 60rpx);
}

.picker-value .arrow {
  color: #999;
  font-size: 28rpx;
  flex-shrink: 0;
  margin-left: 10rpx;
}

/* 地址选择器样式 */
.address-selector {
  width: 100%;
  min-height: 80rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.selected-address {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.address-placeholder {
  font-size: 32rpx;
  color: #999;
  flex: 1;
}

.arrow {
  font-size: 28rpx;
  color: #999;
  margin-left: 10rpx;
}
</style>
